"""
Case Type   : 资源池化
Case Name   : DFX failover操作
Create At   : 2024.01
Owner       : chen
Description :
    1、查询集群初始状态: cm_ctl query -Cvidp
    2、将主机踢出集群: 将对应的gaussdb二进制移除再kill主机(模拟故障)
    3、备机升主: 触发failover操作
Expect      :
    1、集群初始状态正常
    2、主机踢出集群成功
    3、备升主成功
"""

import os
import unittest
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.com = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')

    def test_shared_storage(self):
        text = '-----step1:查询集群初始状态: cm_ctl query -Cvidp;' \
            ' expect: 集群初始状态正常-----'
        self.log.info(text)
        status = self.pri_sh.exec_cm_ctl('query', '-Cvidp')
        self.log.info(status)
        self.assertIn("cluster_state   : Normal", status)
        cur_pri_node = self.pri_sh.get_primary_node()
        self.log.info(cur_pri_node)

        text = '-----step2:将主机踢出集群: 将对应的gaussdb二进制移除再kill主机(模拟故障);' \
            ' expect: 主机踢出集群成功-----'
        self.log.info(text)
        res = self.pri_node.sh(f'''source {macro.DB_ENV_PATH}; 
                mv $GAUSSHOME/bin/gaussdb $GAUSSHOME/bin/gaussdb_bak
                ''').result()
        self.log.info(res)        
        dn_pid1 = self.com.get_pid(self.pri_node, 'bin/gaussdb')
        self.log.info(dn_pid1)

        kill_dn = self.pri_node.sh(f'kill -9 {dn_pid1}').result()
        self.log.info(kill_dn)
        self.assertEqual('', kill_dn, '执行失败: kill dn进程失败')

        text = '-----step3:备机升主: 触发failover操作;' \
            ' expect: 备升主成功-----'
        self.log.info(text)
        status = self.pri_sh.exec_cm_ctl('query', '-Cvidp')
        self.log.info(status)
        cur_pri_node1 = self.pri_sh.get_primary_node()
        self.assertNotEqual(cur_pri_node, cur_pri_node1, '集群异常')
    
    def tearDown(self):
        self.log.info('-----step4: 恢复环境-----')
        res = self.pri_node.sh(f'''source {macro.DB_ENV_PATH}; 
                mv $GAUSSHOME/bin/gaussdb_bak $GAUSSHOME/bin/gaussdb
                ''').result()
        self.log.info(res)
        self.log.info('恢复集群')
        res = self.pri_sh.restart_db_cluster()
        self.log.info(res)
        status = self.pri_sh.exec_cm_ctl('switchover', '-a')
        self.log.info(status)
        self.assertIn(self.constant.cm_switchover_success_msg, status)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
